const coBody = require('co-body');

const parseBody = async (ctx,next)=>{
  ctx.request.body =
        await coBody.form(ctx);
  await next();
};

//coBody.form(ctx)

module.exports = function (router){
  router.get('/',async function(ctx,next){
    ctx.body = view('index',{name:'afda'});
    await next();
  })

  router.get('/test',
        require('./controllers/test.js')
        .get);


  router.post('/test',
        parseBody,
        require('./controllers/test.js')
        .post);


}

let compileMap = new Map();
function view(file,data){
  let template = compileMap.get(file);
  if(template) return template(data);

  const fs = require('fs');
  const handlebars = require('handlebars');
  const fileContents = fs.readFileSync(rootDir+'/views/'+file+'.hbs')
                        .toString();
  template = handlebars.compile(fileContents);
  compileMap.set(file,template);

  return template(data);
}
